package no.gnet.s10.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.gnet.s10.types.JanrainReponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class for Servlet: Controller
 *
 */
 public class JanrainTokenServlet extends GNetController{

	 private static final Object apiKey = "4f8fa96d795716cac4a4728ed5a8d66c336bf27b";

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public JanrainTokenServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String token = (String) request.getParameter("token");
		
		String json = callJanrainBackendWithAuthToken(request.getParameter("token"));
		
		JanrainReponse jrResp = new Gson().fromJson(json, JanrainReponse.class);
		
		//user is logged on ok
		
		try {
			handleJanrainResponse(request, response, jrResp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		establishUserSession(request, response, jrResp.getProfile().getDisplayName());
		
		response.sendRedirect("http://www.sondag10.com");
		
	}

	private void handleJanrainResponse(HttpServletRequest request,
			HttpServletResponse response, JanrainReponse jrResp)
			throws Exception, IOException, ServletException, SQLException {
		String handle = jrResp.getProfile().getPreferredUsername();
		String verifiedEmail = jrResp.getProfile().getVerifiedEmail();
		if(playerWithHandleDoesNotExist(handle)){
			_doCreatePlayer(request, response, "youWillNeverGuessTHIS", handle, handle, verifiedEmail);
			System.out.println("Created "+handle);
			activatePlayer(handle);
			System.out.println("Activated "+handle);
		}
	}

	private boolean playerWithHandleDoesNotExist(String handle) {
		return getPlayer(handle)==null;
	}

	private String callJanrainBackendWithAuthToken(String token) throws IOException {
        URL url = new URL("https://rpxnow.com/api/v2/auth_info");
        Map query = new HashMap();
        query.put("token", token);
        query.put("format", "json");
        query.put("apiKey", apiKey);
        StringBuffer sb = new StringBuffer();
        for (Iterator it = query.entrySet().iterator(); it.hasNext();) {
            if (sb.length() > 0) sb.append('&');
            try {
                Map.Entry e = (Map.Entry)it.next();
                sb.append(URLEncoder.encode(e.getKey().toString(), "UTF-8"));
                sb.append('=');
                sb.append(URLEncoder.encode(e.getValue().toString(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Unexpected encoding error", e);
            }
        }
        String data = sb.toString();
        
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.connect();
        OutputStreamWriter osw = new OutputStreamWriter(
            conn.getOutputStream(), "UTF-8");
        osw.write(data);
        osw.close();
        BufferedReader br =new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line=null;
        String tot = "";
        while((line=br.readLine())!=null){
        	System.out.println(line);
        	tot=tot+line;
        }
		JanrainReponse jrResp = new Gson().fromJson(tot, JanrainReponse.class);
		
		System.out.println("Resp: "+ jrResp);        
		return tot;
	}


	public static void main(String [] a) throws IOException{
		new JanrainTokenServlet().callJanrainBackendWithAuthToken(a[0]);
		
//		String t="{\"profile\":{\"googleUserId\":\"102943297533832892745\","+
//		"\"verifiedEmail\":\"gautesmaaland@gmail.com\",\"name\":{\"givenName\":\"Gaute\","+
//				"\"familyName\":\"Smaaland\",\"formatted\":\"Gaute " +
//				"Smaaland\"},\"displayName\":\"gautesmaaland\",\"preferredUsername\":\"gautesmaaland\"," +
//				"\"providerName\"" +
////				":\"Google\"},\"stat\":\"ok\"}";
//		BufferedReader br = new BufferedReader(new FileReader("C:\\data\\test.json.txt"));
//		String t = br.readLine();
//		JanrainReponse jrResp = new Gson().fromJson(t, JanrainReponse.class);
//		
//		System.out.println("Resp: "+ jrResp);        
		
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().println("Sorry, GET not supported");
	}  	
	
}